package com.pratik.android.smssniffer.handlers.impl;


import com.pratik.android.smssniffer.handlers.MessageHandlerService;
import com.pratik.android.smssniffer.handlers.dto.AppMessageCodes;
import com.pratik.android.smssniffer.handlers.dto.CodeSMS;

import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

class MessageHandlerServiceImpl implements MessageHandlerService {
	
	@Override
	public String obtainMessage(Intent intent) {
		SmsMessage[] sms = obtainSMS(intent);
		return createStringMessage(sms);
	}
	
	@Override
	public String obtainIncomingPhoneNumber(Intent intent) {
		SmsMessage[] sms = obtainSMS(intent);
		String number = null;
		if (sms[0] != null) {
			try {
				number = sms[0].getOriginatingAddress();
			} catch (ArrayIndexOutOfBoundsException e) {
				e.printStackTrace();
			}
		}

		return number;
	}

	
	@Override
	public Boolean isAppMessage(String message) {
        
		if (message.length() >= 6) {
			String[] extractMessage = message.split(":");
			
			if (extractMessage.length >= 1) {
				if (AppMessageCodes.DELETE_RECENT_MSG_REQ_CODE.getCode().equalsIgnoreCase(extractMessage[0])
						) {
					return true;
				}
			}
		}
		return false;
	}
	
	@Override
	public CodeSMS extractMessage(String message) {
		
		if (message.length() >= 6) {
			
			String[] extractMessage = message.split(":");

			if (extractMessage.length >= 2) {
				CodeSMS cs = new CodeSMS();
				cs.setCode(extractMessage[0]);
				cs.setSmsBody(extractMessage[1]);
				return cs;
			}
		}
		
		return null;
	}
	
	
	
	private String createStringMessage(SmsMessage[] sms) {
		String message = "";
		for (int i = 0; i < sms.length; i++) {
			
			message += sms[i].getMessageBody().toString();
		}

		return message;
	}

	private SmsMessage[] obtainSMS(Intent intent) {

		Bundle bundle = intent.getExtras();
		SmsMessage[] sms = null;
		Object[] pdus = (Object[]) bundle.get("pdus");
		sms = new SmsMessage[pdus.length];

		for (int i = 0; i < sms.length; i++) {
			sms[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
		}

		return sms;
	}

}
